var config = require('./config');
var ObjectID = require('mongodb').ObjectID;
var MongoClient = require('mongodb').MongoClient;
var logger = require('./logger');

function DB() {
    this.loginCollection = 'LoginLog';
    this.adminCollection = 'Admin'; //用户
    this.sessionCollection = 'Session';//session
    this.webInfoCollection = 'WebInfo';//网站配置信息
    this.webCollection = 'Web';//网站
    this.adCollection = 'Ad';//网站广告
    this.talkCollection = 'Talk';//留言
    this.noticeCollection = 'Notice';//留言

    this.db = null;
    this.pagesize = 20;
}

DB.prototype.connect = function (cb) {
    var self = this;
    MongoClient.connect(config.connectionStr, function (err, db) {
        self.db = db;
        cb(err);
    });
};

//DB.prototype.close = function (cb) {
//    this.db.close(cb);
//};

DB.prototype.getIdFromStr = function (id) {
    var ret = "";
    if (id){
        ret = new ObjectID.createFromHexString(id);
    }
    return ret;
};

DB.prototype.getConnection = function (cb) {
    if (this.db) {
        cb(null, this.db);
    } else {
        var self = this;
        this.db = null;
        logger.info('reconnect to mongodb');
        self.connect(function (err) {
            cb(err, self.db);
        });
    }
};

DB.prototype.getSession = function (req,sessionId,cb) {
    var self = this;
    if (self.db) {
        self.db.collection(self.sessionCollection).findOne({id:sessionId}, function (err,session) {
            if(err){
                cb(err);
            }else{
                if(!session){
                    cb(new Error(config.ErrorStr.needLogin));
                }else{
                    //logger.info('session check:%d,%d,%d,%d',Date.now(),session.date,Date.now() - session.date,config.sessionTimeout);

                    //if(Date.now() - session.date > config.sessionTimeout){ //session 过期
                    //    self.db.collection(self.sessionCollection).remove({_id:session._id}, function (err) {
                    //        req.cookies.clearCookie(config.sessionName);
                    //        if(err){
                    //            cb(err);
                    //        }else{
                    //            cb(new Error(config.ErrorStr.needLogin));
                    //        }
                    //    });
                    //}else{
                    //    cb(null,session);
                    //}
                    cb(null,session);
                }
            }
        });
    } else {
        cb(new Error(config.ErrorStr.connErr));
    }
};

DB.prototype.removeExpiredSession = function(cb){
    var self = this;
    if (self.db) {
        var expired = Date.now() - config.sessionTimeout;
        self.db.collection(self.sessionCollection).remove({date:{$lt:expired}}, function (err,count) {
            if(err){
                logger.error(err.stack);
            }else{
                logger.info('remove expired session:',count);
            }
            cb();
        });
    }else{
        cb();
    }
};

DB.prototype.updateSession = function (sessionId,cb) {
    var self = this;
    if (this.db) {
        this.db.collection(self.sessionCollection).update({id:sessionId},{$set:{date:Date.now()}},function (err) {
            if(err){
                cb(err);
            }else{
                cb();
            }
        });
    } else {
        cb(new Error(config.ErrorStr.connErr));
    }
};

DB.prototype.createSession = function (userInfo,cb) {
    var self = this;
    if (this.db) {
        var timestamp = (Date.now() + Math.ceil(Math.random() * 1000)).toString();
        var obj = {uid:userInfo._id,id:timestamp,right:userInfo.right,gid:userInfo.gid};
        self.db.collection(self.sessionCollection).findOne(obj, function (err,oldSession) {
            if(err){
                cb(err);
            }else{
                if(oldSession){
                    self.db.collection(self.sessionCollection).update({_id:oldSession._id},{$set:{date:Date.now()}}, function (err,success) {
                        logger.info('has old session:%j,%j',err,success);
                        if(err){
                            cb(err);
                        }else{
                            cb(null,obj.id);
                        }
                    });
                }else{
                    obj.date = Date.now();
                    self.db.collection(self.sessionCollection).insert(obj, function (err,newSession) {
                        logger.info('insert new session:%j,%j',err,newSession);
                        if(err){
                            cb(err);
                        }else{
                            cb(null,obj.id);
                        }
                    });
                }
            }
        });
    } else {
        cb(new Error(config.ErrorStr.connErr));
    }
};

DB.prototype.clearSession = function (uid,cb) {
    var self = this;
    if (this.db) {
        this.db.collection(self.sessionCollection).remove({uid:self.getIdFromStr(uid)}, function (err) {
            if(err){
                cb(err);
            }else{
                cb();
            }
        });
    } else {
        cb(new Error(config.ErrorStr.connErr));
    }
};

module.exports = exports = new DB;